﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    public bool isLocalPlayer = true;
    public string username;

    public GameObject playerPrefab;

    private SyncPositionRequest syncPositionRequest;
    private SyncPlayerRequest syncPlayerRequest;

    private Vector3 lastPosition = Vector3.zero;
    private float moveOffset = 0.1f;

    private Dictionary<string, GameObject> playerDict = new Dictionary<string, GameObject>();

    void Start()
    {
        if (isLocalPlayer == true)
        {
            GetComponent<Renderer>().material.color = Color.green;
            syncPositionRequest = GetComponent<SyncPositionRequest>();
            syncPlayerRequest = GetComponent<SyncPlayerRequest>();
            syncPlayerRequest.DefaultRequest();

            InvokeRepeating("SyncPosition", 1, 0.1f);
        }
        else
        {

        }
    }

    void SyncPosition()
    {
        if (Vector3.Distance(transform.position, lastPosition) > 0.1f)
        {
            lastPosition = transform.position;
            syncPositionRequest.pos = transform.position;
            syncPositionRequest.DefaultRequest();
        }
    }

    void Update()
    {
        if (isLocalPlayer)
        {
            float h = Input.GetAxis("Horizontal");
            float v = Input.GetAxis("Vertical");
            transform.Translate(new Vector3(h, 0, v) * Time.deltaTime * 4);
        }
    }

    public void OnSyncPlayerResponse(List<string> usernameList)
    {
        foreach (string username in usernameList)
        {
            OnNewPlayerEvent(username);
        }
    }

    public void OnNewPlayerEvent(string username)
    {
        GameObject go = GameObject.Instantiate(playerPrefab);
        Destroy(go.GetComponent<SyncPlayerRequest>());
        Destroy(go.GetComponent<SyncPositionRequest>());
        Destroy(go.GetComponent<NewPlayerEvent>());
        go.GetComponent<Player>().isLocalPlayer = false;
        go.GetComponent<Player>().username = username;
        
        playerDict.Add(username, go);
    }
}
